var globals = require('./globals.js');

exports.route = route;

function route(formMethod, controller, actionMethod, args, baseUrl)
{
  this.formMethod = formMethod;
  this.controller = controller;
  this.actionMethod = actionMethod;
  this.args = args;
  var subExpressions = (args !== '' && args !== undefined && args !== null) ? compilequerystringandparameterstoregularexpression(args): '';
  this.regExpForParams = (subExpressions !== '' && subExpressions !== undefined && subExpressions !== null) ? new RegExp(subExpressions, 'g') : '';
  this.regExp = new RegExp(compile(baseUrl, controller, actionMethod, subExpressions), 'i');
};

function compile(baseUrl, controller, actionMethod, subExpressions)
{
  var regExp = '(^' + (baseUrl === '/'? '' : baseUrl) + '\/' + controller + '\/' + actionMethod;
  regExp += subExpressions;
  regExp += ')$';
  return regExp;

}

function compilequerystringandparameterstoregularexpression (args) {
  var regExp = '';
  splitString = args.split('/');
  splitString.forEach(function(string, index, array){
    if(string !== '' && string!== undefined && string !== null && !string.includes('{')){
      regExp += (index === 1? '((\\/)|(\\?))' :'((\\/)|(\\&))') + string;
    }

    //Includes both arguments and regular expression string.
    else if (string.includes('{') && string.includes('(')){
      regExp += '((\\/)|(\\=))(([^\\/]' + string.split('(')[1].split(')')[0] + '*(\\/$))|([^\\/]' + string.split('(')[1].split(')')[0] + '*))';
    }

    //Includes only the id part of the parameter
    else if (string.includes('{'))  {
      regExp += '((\/)|(\\=))' + '(([^\\/]*(\\/$))|([^\\/]*))';
    }
    
  });
  return regExp;
}